<template>
  <ele-page flex-table>
    <ComHeader :title="`调拨单详情[${info?.order_sn}]`" @back="goBack" />
    <ele-bottom-bar v-if="hasActs(info)" :teleported="true">
      <template #extra>
        <el-button v-if="info.is_edit === 1" type="primary" plain @click="onCommand('EDIT')">编辑</el-button>
        <el-button v-if="info.is_sl === 1" type="primary" plain @click="onCommand('SH')">审核</el-button>
        <el-button v-if="info.is_fs === 1" type="danger" plain @click="onCommand('FS')">反审</el-button>
        <el-button v-if="info.is_ph === 1" type="danger" plain @click="onCommand('PH')">配货</el-button>
        <el-button v-if="info.is_ok === 1" type="primary" plain @click="onCommand('OK')">结单</el-button>
        <el-button v-if="info.is_cd === 1" type="info" @click="onCommand('CD')">取消</el-button>
      </template>
    </ele-bottom-bar>

    <ele-card flex-table bordered :header-style="{ padding: '0 16px' }">
      <el-scrollbar>
        <div>
          <el-descriptions title="" :column="4">
            <el-descriptions-item :width="100" label="要货单号">
              <ele-copyable>{{ info.order_sn }}</ele-copyable>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="第三方单号">
              <ele-copyable>{{ info.third_party_sn }}</ele-copyable>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="货主">
              {{ info.supplier_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="对外平台">
              {{ info.su_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="订单状态">
              <el-tag v-if="info.status_name" :type="getType(info.status)">
                {{ info.status_name }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="收货状态">
              <el-tag v-if="info.enter_status_name" :type="getType(info.enter_status)">
                {{ info.enter_status_name }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="品数">
              {{ info.product_num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="调拨数量">
              {{ info.num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="收货数量">
              {{ info.enter_num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="单据日期">
              {{ info.order_date }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建人">
              {{ info.create_user_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建时间">
              {{ info.create_time ? formatDate(info.create_time) : '-' }}
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="备注">
              {{ info.remark || '-' }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions class="mt-20px" title="商品信息" :column="1" />

          <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="{ product }" :rules="rules" label-width="auto">
            <el-form-item label="" label-position="top" label-width="200px" prop="product">
              <el-table
                :data="product"
                border
                style="width: 100%"
                show-summary
                :summary-method="getSummaries"
                class="form-table"
                row-key="product_id"
              >
                <el-table-column type="index" label="序" width="60" align="center" />
                <el-table-column prop="product_name" label="商品名称" align="left" min-width="120" />
                <el-table-column prop="product_code" label="商品编码" align="center" />
                <el-table-column prop="price" label="商品价格" align="center" />
                <el-table-column prop="unit" label="单位" align="center" />

                <!-- <el-table-column prop="unit_list" label="单位转换" align="center" min-width="100">
                  <template #default="{ row }">
                    <div class="flex-wrap flex-ca text-#555">
                      <div v-for="(item, i) in formatUnitList(row.unit_list)" :key="i" class=""><span v-if="i" class="mx-3px">=</span>{{ item.ratio_num }}{{ item.unit }}</div>
                      <div v-if="!formatUnitList(row.unit_list).length">-</div>
                    </div>
                  </template>
                </el-table-column> -->
                <el-table-column prop="num" label="调拨数量" align="center" />
                <el-table-column prop="warehouse" label="调拨明细" align="center" min-width="120">
                  <template #default="{ row }">
                    <div v-for="v in row.warehouse" :key="v.warehouse_id" class="flex-ca leading-20px">
                      <div>{{ v.warehouse_name }}：</div>
                      <div class="flex-a">
                        <div v-for="(item, i) in v.multi_unit.filter(v => v.num > 0)" :key="i">
                          <span v-if="i">、</span>{{ item.num || 0 }}{{ item.unit }}
                        </div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="enter_num" label="发货数量" align="center" />
              </el-table>
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
    </ele-card>

    <PageReview
      v-model="showReview"
      remarkDisabled
      :statusList="[
        {
          value: 'SL',
          label: '受理',
        },
        {
          value: 'JJ',
          label: '拒绝',
        },
      ]"
      @done="review"
    />
  </ele-page>
</template>

<script setup>
import PageReview from '@/components/Common/Review.vue'

defineOptions({ name: 'OpenTransferInfo' })

const orderId = ref(0)
const route = useRoute()
const router = useRouter()
const { routeTabKey, removePageTab, setPageTabTitle, addPageTab } = utils.usePageTab()
const { formatDate, getType } = utils
const info = ref({ product_list: [] })
const showReview = ref(false)

const { hasActs } = utils
const formRef = ref(null)

const rules = reactive({})

// const loading = ref(false)

const product = ref([])

onMounted(() => {
  orderId.value = route.params?.id
  getInfo()
})

function goBack() {
  removePageTab({ key: routeTabKey })
  router.push('/open/transfer')
}

function updateStatus(url, formData, cb) {
  const loadingBox = utils.message('请求中..', 'loading')
  utils.post(url, formData).then((res) => {
    utils.message(res.msg, res.success)
    if (res.success) {
      getInfo()
      showReview.value = false
    }
  }).finally(() => {
    cb && cb()
    loadingBox.close()
  })
}

function review(data, cb) {
  updateStatus('/apiTransfer/review', {
    status: data.status,
    id: info.value.id,
  }, cb)
}

async function onCommand(command) {
  command = command.toUpperCase()

  if (['EDIT'].includes(command)) {
    const path = `/open/transfer/${command.toLowerCase()}/${info.value.id}`
    addPageTab({
      key: path,
      closable: true,
    })
    router.push(path)
  }
  else if (command === 'SH') {
    showReview.value = true
  }
  else {
    // PH 配货， FS 反审， OK 已结单
    const list = [
      { key: 'CD', title: '取消' },
      { key: 'PH', title: '配货' },
      { key: 'FS', title: '反审' },
      { key: 'OK', title: '结单' },
    ]
    const item = list.find(v => v.key === command)
    const otps = {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
    if (command === 'CD') {
      otps.ancelButtonText = '不取消了'
      otps.confirmButtonText = '确定取消'
    }
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">${item.title}</span>订单吗`, '系统提示', otps).then(() => {
      updateStatus('/apiTransfer/review', { id: info.value.id, status: command })
    })
  }
}

function getInfo() {
  utils.get('/apiTransfer/Info', { id: orderId.value }).then((res) => {
    info.value = res.data
    product.value = res.data.product
    setPageTabTitle(`要货单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
  })
}

function formatUnitList(data = []) {
  if (data?.length < 2)
    return []

  data.sort((a, b) => a.ratio - b.ratio)
  const ratio = data[data.length - 1].ratio
  data.forEach((v) => {
    v.ratio_num = utils.Big(ratio).div(v.ratio).round(4).valueOf()
  })
  return data
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['num', 'enter_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => {
        const num = column.property === 'num' ? cur[column.property] : cur[column.property]
        return utils.Big(acc).plus(num).valueOf()
      }, 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
